﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Eugenhome.Atrium.Rss
{
    /// <summary>
    /// 
    /// </summary>
    public class RssSource
    {
        /// <summary></summary>
        public int ID { get; set; }

        /// <summary></summary>
        public string Name { get; set; }

        /// <summary></summary>
        public string Url { get; set; }

        /// <summary></summary>
        public List<int> Readed { get; set; }

        /// <summary></summary>
        public DateTime LastReaded { get; set; }


        /// <summary></summary>
        [XmlIgnore]
        public RssCollection Items { get; private set; }

        /// <summary></summary>
        [XmlIgnore]
        public List<string> Errors = new List<string>();

        /// <summary></summary>
        private string _proxyAddress = "";

        /// <summary></summary>
        private RssSourceCollection _parentCollection;

        /// <summary>
        /// 
        /// </summary>
        public RssSource() { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="url"></param>
        /// <param name="name"></param>
        /// <param name="proxyAddress"></param>
        public RssSource(int id, string url, string name, string proxyAddress)
        {
            Url = url;
            ID = id;
            Name = name;
            Readed = new List<int>();
            LastReaded = DateTime.MinValue;
            _proxyAddress = proxyAddress;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentCollection"></param>
        /// <param name="proxyAddress"></param>
        internal void Init(RssSourceCollection parentCollection, string proxyAddress)
        {
            _parentCollection = parentCollection;
            _proxyAddress = proxyAddress;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="readedIncl"></param>
        /// <param name="itemdatabind"></param>
        /// <returns></returns>
        public RssCollection DataBind(bool readedIncl, bool itemdatabind)
        {
            Items = new RssCollection(_proxyAddress);
            Items.DataBind(Url, itemdatabind);

            Errors.AddRange(Items.Errors);

            if (!readedIncl)
            {
                //Items.Delete(Readed);
                Items.DeleteOld(LastReaded);
            }

            return Items;
        }

        /// <summary>
        /// 
        /// </summary>
        public void SetReaded(DateTime pubDate)
        {
            if (!Items.Count.Equals(0))
            {
                LastReaded = pubDate;

                _parentCollection.Save();

                Items.Clear();
            }
        }

    }
}
